﻿using System.ComponentModel;
using System.Web.Mvc;
using ShopB2C.Entity;
using ShopB2C.Helper;
using ShopB2C.Interfaces;
using ShopB2C.ViewModels;

namespace ShopB2C.Controllers.Manager {
    /// <summary>
    /// 新闻
    /// </summary>
    public partial class NewsController : BaseController {

        private static INews _news;
        private static IClassify _classify;
        private const string _moduleKey = "News";

        public NewsController() {
            this.PageSize = 13;
            _news = DataBaseExecuter.CreateClassByName<INews>("News");
            _classify = DataBaseExecuter.CreateClassByName<IClassify>("Classify");
        }

        #region News

        public ActionResult NewsList([DefaultValue(1)]int number) {
            int pageCount;
            string classifyIdRequest = Request["Classify"];
            string key = Request["Key"];
            int classifyId = string.IsNullOrEmpty(classifyIdRequest)
                ? 0
                : int.Parse(classifyIdRequest);
            return View(new NewsViewModel() {
                NewsList = _news.GetNewsList(classifyId, key, this.PageSize, number, out pageCount),
                ClassifyList = _classify.GetClassifyByModuleKey(_moduleKey),
                News = new NewsEntity(),
                PageNumber = number,
                ClassifyId = classifyId,
                Key = key,
                Pager = this.CreatePager(Url.Action("NewsList", new {
                    number = "{0}",
                    Classify = classifyId,
                    Key = key
                }), pageCount, number)
            });
        }

        public ActionResult NewsEdit([DefaultValue(1)]int number, [DefaultValue(0)]int id) {
            return View(new NewsViewModel() {
                News = id == 0 ? new NewsEntity() : _news.GetNewsById(id),
                PageNumber = number,
                ClassifyList = _classify.GetClassifyByModuleKey(_moduleKey)
            });
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult NewsEdit([DefaultValue(1)]int number, NewsViewModel nvm) {
            NewsEntity ne = nvm.News;
            if (ne.NewsId == 0) {
                _news.NewsAppend(ne);
            }
            else {
                _news.NewsUpdate(ne);
            }
            return this.RedirectToAction("NewsEdit", new { number = number, id = ne.NewsId });
        }

        public ActionResult NewsDelete(string ids) {
            _news.NewsDelete(ids);
            return RedirectToAction("NewsList");
        }

        #endregion

    }
}